/**
 * @Question.Title: 递增顺序搜索树
 * @Question.No: 897
 * @Author: Dang Qi
 * @Date: 2021-04-25 15:43:04
 * @Description: 
 */
//给你一棵二叉搜索树，请你 按中序遍历 将其重新排列为一棵递增顺序搜索树，使树中最左边的节点成为树的根节点，并且每个节点没有左子节点，只有一个右子节点。 
//
// 
//
// 示例 1： 
//
// 
//输入：root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
//输出：[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
// 
//
// 示例 2： 
//
// 
//输入：root = [5,1,7]
//输出：[1,null,5,null,7]
// 
//
// 
//
// 提示： 
//
// 
// 树中节点数的取值范围是 [1, 100] 
// 0 <= Node.val <= 1000 
// 
// Related Topics 树 深度优先搜索 递归 
// 👍 193 👎 0

package dq.leetcode.editor.cn;

import com.dq.tree.Tree;
import com.dq.tree.TreeNode;
import com.dq.tree.TreeUtil;

public class IncreasingOrderSearchTree {
    public static void main(String[] args) {
        Solution solution = new IncreasingOrderSearchTree().new Solution();
        TreeNode tree = Tree.proATree(new Integer[]{5,3,6,2,4,null,8,1,null,null,null,7,9});
        TreeUtil.pirnt(tree);
        tree = solution.increasingBST(tree);
        for(;tree!=null;tree = tree.right){
            System.out.print(tree.val + " ");
        }
    }
        //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private TreeNode pre = null;
    private TreeNode head = null;
    public TreeNode increasingBST(TreeNode root) {
        increasingBST2(root);
        return head;
    }
    public void increasingBST2(TreeNode root) {
        if(root == null) return;
        increasingBST2(root.left);
        root.left = null;
        if(head==null) {
            pre = root;
            head = root;
        } else{
            pre.right = root;
            pre = root;
        }
        increasingBST2(root.right);
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}